/* eslint-disable @next/next/no-img-element */
import styles from '../styles/Home.module.scss'
import { GetServerSideProps } from 'next'
import * as React from 'react'
import { IArticle, IUser } from '../types'
import * as userService from '../services/user.service'
import { Button, Select } from 'antd'
import 'antd/dist/antd.css'
import { useRouter } from 'next/router'
import toast from '../components/Toast'
import Header from '../components/header'
import ArticleItem from '../components/articleItem'

const { Option } = Select

interface Props {
  user: IUser
  articles: IArticle[]
}

export const getServerSideProps: GetServerSideProps = async ctx => {
  const result = await userService.userInfo(ctx.req.cookies.token)
  const list = await userService.articles()
  list.rows.sort((a: IArticle, b: IArticle) => {
    return new Date(b.time).valueOf() - new Date(a.time).valueOf()
  })
  if (result.stat === 'OK') {
    return {
      props: {
        user: result.data,
        articles: list.rows
      }
    }
  } else {
    return {
      props: {
        user: null,
        articles: list.rows
      }
    }
  }
}

export default function Home(props: Props) {
  const [rows, setRows] = React.useState<IArticle[]>(props.articles)
  const router = useRouter()

  function handleChange(value: string) {
    switch (value) {
      case '按时间':
        const newrows = rows.sort((a: IArticle, b: IArticle) => {
          return new Date(b.time).valueOf() - new Date(a.time).valueOf()
        })
        setRows([...newrows])
        return
      case '按浏览量':
        const newrows2 = rows.sort((a: IArticle, b: IArticle) => {
          return b.views - a.views
        })
        setRows([...newrows2])
        return
      case '按热度':
        const newrows3 = rows.sort((a: IArticle, b: IArticle) => {
          return b.likes - a.likes
        })
        setRows([...newrows3])
    }
  }

  const postArticle = async () => {
    if (props.user === null) {
      toast('请登录')
      router.push('/login')
    } else {
      router.push('/post')
    }
  }

  return (
    <>
      <Header user={props.user} />
      <div className={styles.back}>
        <div className={styles.main}>
          <div className={styles.nav}>
            <Select
              className={styles.select}
              defaultValue="按时间"
              style={{ width: 120 }}
              onChange={handleChange}
            >
              <Option value="按时间">按时间</Option>
              <Option value="按浏览量">按浏览量</Option>
              <Option value="按热度">按热度</Option>
            </Select>
            <Button className={styles.post} size="large" onClick={postArticle}>
              发布文章
            </Button>
          </div>
          <div className={styles.articles}>
            {rows.map((item, index) => {
              return <ArticleItem key={index} item={item} />
            })}
          </div>
        </div>
      </div>
    </>
  )
}
